<?php
session_start();
require_once("./dbConnect.inc");

if (isset($_POST['submit'])) {
  processLogin();
} elseif (isset($_GET["action"]) and $_GET["action"] == "logout") {
    logout();
} else {
  //doe niets
}

function processLogin() {
  global $databaseConnection;
  if (!isset($_POST['suppliedusername']) or !isset($_POST['suppliedpassword'])) {
    $_SESSION['statusmessage'] = "U moet een geldige gebruikersnaam en wachtwoord invoeren!";
  } else {
    $suppliedusername = $_POST['suppliedusername'];
    $suppliedpassword = $_POST['suppliedpassword'];

    $qUser = "SELECT fullname, username, password FROM gebruikers where username = '$suppliedusername'";
    $queryResult = mysqli_query($databaseConnection, $qUser);

    if (mysqli_num_rows($queryResult) == 1) {
      while ($row = mysqli_fetch_array($queryResult, MYSQLI_ASSOC)) {
        if (md5($suppliedpassword) == $row["password"]) {
          $_SESSION["statusmessage"] = $row["fullname"];
          $_SESSION["username"] = $row["username"];
        } else {
          $_SESSION["statusmessage"] = "Gebruikersnaam en/of wachtwoord zijn onjuist!";
        }
      }
    } else {
      $_SESSION["statusmessage"] = "$suppliedusername is niet bekend.";
    }

    unset($_POST["submit"]);
  }
}

function logout() {
  unset( $_SESSION["username"] );
  unset( $_SESSION["statusmessage"] );
  session_write_close();
}

// in all cases return to mainpage.
header("Location: index.php");
?>